<template>
  <div style="display: flex;">
    <div style="width:30%;  border: 1px solid rgb(217, 217, 217);padding:10px">
      <div class="auth-app-title">应用列表({{ app.pagination.total }})</div>
      <a-input-search placeholder="请输入应用名称、应用编码"
                      allow-clear
                      @search="appSearch" />
      <a-menu style="max-height: 500px;"
              :default-selected-keys="['1']"
              :default-open-keys="['sub1']"
              mode="inline"
              @select="appSelect"
              :inline-collapsed="false">
        <a-menu-item v-for="item in app.data"
                     :key="item.id">
          <span>{{ item.name }}</span>
        </a-menu-item>
      </a-menu>
      <a-pagination style="text-align: center;margin-top:10px;"
                    @change="appChangePage"
                    :total="app.pagination.total"
                    v-model="app.pagination.current"
                    show-size-changer
                    :pageSizeOptions="app.pagination.pageSizeOptions"
                    size="small"
                    :page-size="app.pagination.pageSize"
                    @showSizeChange="appSizeChange"
                    show-less-items />
    </div>
    <div style="width:20%;border: 1px solid rgb(217, 217, 217);padding:10px;margin-left:20px">
      <div class="auth-app-title">选择机构</div>
      <a-tree style="overflow-y:auto;max-height: 500px"
              ref="unitTree"
              @select="treeSelect"
              :selectedKeys="unit.selectedKeys"
              :showIcon="true"
              :tree-data="unit.treeData">
        <a-icon slot="switcherIcon"
                type="caret-down" />
        <a-icon slot="clazz"
                type="appstore" />
        <a-icon slot="unit"
                type="home" />
        <a-icon slot="dept"
                type="bank" />
        <template #title="item">
          <a-dropdown :trigger="['contextmenu']">
            <span v-if="item.treeTitle.indexOf(unit.searchValue) > -1">
              {{ item.treeTitle.substr(0, item.treeTitle.indexOf(unit.searchValue)) }}
              <span style="color: #f50">{{ unit.searchValue }}</span>
              {{ item.treeTitle.substr(item.treeTitle.indexOf(unit.searchValue) + unit.searchValue.length) }}
            </span>
            <span v-else>{{ item.treeTitle }}</span>
          </a-dropdown>
        </template>
      </a-tree>
    </div>

    <div style="width:50%;border: 1px solid rgb(217, 217, 217);padding:10px;margin-left:20px">
      <div class="auth-app-title">授权用户</div>
      <a-transfer show-search
                  :filter-option="(inputValue, item) => item.userName.indexOf(inputValue) !== -1 || item.account.indexOf(inputValue) !== -1"
                  :rowKey="record => record.unitUserId"
                  :titles="user.titles"
                  :targetKeys="user.targetKeys"
                  @change="onChange"
                  :dataSource="user.dataSource">
        <template slot="children"
                  slot-scope="{
                    props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                    on: { itemSelectAll, itemSelect },
                  }">
          <a-table :row-selection="
                     getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                   "
                   :columns="direction === 'left' ? user.columns : user.columns"
                   :data-source="filteredItems"
                   size="small"
                   :custom-row="
                     ({ key, disabled: itemDisabled }) => ({
                       on: {
                         click: () => {
                           if (itemDisabled || listDisabled) return;
                           itemSelect(key, !selectedKeys.includes(key));
                         },
                       },
                     })
                   " />
        </template>
      </a-transfer>
      <a-button style="margin: 30px auto 0 auto;display: block;"
                type="primary"
                @click="saveAppUser"
                class="btn">保存</a-button>
    </div>

  </div>

</template>
<script>
import difference from 'lodash/difference'
import { PAGINATION } from '../../constants'
import { page, saveAppUser, getAuthList } from '../../api/application/index'
import { getAuthUnitTree } from '../../api/unit'
import { sysApplicationUserList } from '../../api/user/index'
export default {
  name: 'appAuthUser',
  data () {
    return {
      app: {
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          pageSizeOptions: ['10', '20', '30', '50'],
          appId: ''
        },
        params: {
          keyword: ''
        },
        data: []
      },
      selectAppKey: '',
      unit: {
        treeData: [],
        expandedKeys: [],
        selectedKeys: [],
        dataList: [],
        searchValue: ''
      },
      user: {
        targetKeys: [],
        dataSource: [],
        titles: ['已授权', '未授权'],
        pagination: PAGINATION,
        dataList: [],
        selectedRowKeys: [],
        searchValue: '',
        count: 0,
        columns: [
          {
            title: '姓名',
            dataIndex: 'userName',
            align: 'center',
            ellipsis: true
          },

          {
            title: '部门',
            dataIndex: 'deptName',
            align: 'center',
            ellipsis: true
          }

        ]
      }
    }
  },
  created () {
    this.initApp()
  },
  mounted () { },
  methods: {
    initApp () {
      this.app.params.currPage = this.app.pagination.current
      this.app.params.pageSize = this.app.pagination.pageSize
      this.user.pagination.total = 0
      page(this.app.params).then((res) => {
        this.app.data = res.list
        this.app.pagination.total = res.totalCount
      })
    },
    appSearch (value) {
      this.app.params.keyword = value
      this.app.pagination.current = 1
      this.app.pagination.pageSize = 10
      this.initApp()
    },
    appChangePage (current, pageSize) {
      this.app.pagination.current = current
      this.app.pagination.pageSize = pageSize
      this.initApp()
    },
    appSizeChange (current, size) {
      this.app.pagination.current = 1
      this.app.pagination.pageSize = size
      this.initApp()
    },
    appSelect ({ item, key, selectedKeys }) {
      this.selectAppKey = key
      this.unit.expandedKeys = []
      this.unit.selectedKeys = []
      this.initUnitTree()
      this.user.pagination.applicationId = key
      this.user.pagination.unitId = null
      this.user.pagination.current = 1
      this.user.pagination.pageSize = 10
      this.user.searchValue = ''
      this.user.targetKeys = []
      this.user.dataSource = []
      this.initUser()
    },
    initUnitTree () {
      getAuthUnitTree(this.selectAppKey).then((response) => {
        if (response) {
          this.unit.treeData = response
        } else {
          this.unit.treeData = []
        }
      })
    },
    treeExpand (expandedKeys, info) {
      this.unit.autoExpandParent = false
      this.unit.expandedKeys = expandedKeys
    },
    initUser () {
      sysApplicationUserList(this.user.pagination).then((res) => {
        this.user.dataSource = res
      })
      getAuthList({ applicationId: this.selectAppKey }).then((res) => {
        if (res) {
          this.user.targetKeys = res
        }
      })
    },
    treeSelect (selectedKeys) {
      this.user.pagination.unitId = selectedKeys[0]
      this.unit.selectedKeys = selectedKeys
      this.user.searchValue = ''
      if (this.selectAppKey) {
        this.initUser()
      }
    },
    userHandleTableChange (pagination, b) {
      this.user.pagination = pagination
      this.initUser()
    },
    onUserChange (selectedRowKeys, selectedRows) {
      this.user.selectedRowKeys = selectedRowKeys
      this.user.count = this.user.selectedRowKeys.length
    },
    saveAppUser () {
      saveAppUser({
        applicationId: this.selectAppKey,
        unitUserIds: this.user.targetKeys
      }).then((res) => {
      })
    },
    userSearch (value) {
      this.user.searchValue = value
      this.user.pagination.current = 1
      this.user.pagination.pageSize = 10
      this.user.pagination.total = 0
      this.initUser()
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },
    onChange (nextTargetKeys) {
      this.user.targetKeys = nextTargetKeys
    }
  }
}
</script>

<style scoped>
.auth-app-title {
  border: 1 px solid rgb(217, 217, 217);
  margin-bottom: 3 px;
  border-radius: 50 px;
  height: 30 px;
  line-height: 30px;
  text-align: center;
  font-weight: 1000;
}
.ant-menu-inline {
  border-right: 0;
}
</style>
